package com.lihepeng.leecode.solid_aim_offer.linkedlist;

import com.lihepeng.leecode.linkedList.ListNode;
import org.junit.Test;

/**
 * 删除链表中的节点
 * 2022年5月4日
 *
 */
public class Solution18 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param val int整型
     * @return ListNode类
     */
    public ListNode deleteNode (ListNode head, int val) {
        if (head == null) {
            return null;
        }
        ListNode dumpNode = new ListNode(-1);
        dumpNode.next = head;
        ListNode headNode = dumpNode;
        while (headNode!=null) {
            if (headNode.value == val) {
                // 删除
                ListNode nextNode =  headNode.next;
                if (nextNode!=null) {
                    // 删除当前节点
                    headNode.value = nextNode.value;
                    headNode.next = nextNode.next;
                }else {
                    headNode = null;
                }
            }
            headNode = headNode.next;
        }
        return dumpNode.next;
    }
    @Test
    public void runTest() {
        ListNode head = new ListNode(0);
        ListNode head1 = new ListNode(1);
        ListNode head2 = new ListNode(2);
        ListNode head3 = new ListNode(3);
        ListNode head4 = new ListNode(4);
        ListNode head5 = new ListNode(5);
        head.next = head1;
        head1.next = head2;
        head2.next = head3;
        head3.next = head4;
        head4.next = head5;
        ListNode listNode = deleteNode(head, 1);
        while (listNode!=null) {
            System.out.println(listNode.value);
            System.out.println("-->");
            listNode = listNode.next;
        }

    }
}
